package com.china.produce.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2022/8/6
 */
@Slf4j
@Configuration
public class ThreadPoolConfig {

    @Bean("thread-pool-task")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        //核心线程数目
        executor.setCorePoolSize(4);

        //最大线程数目
        executor.setMaxPoolSize(8);

        //队列中最大数目
        executor.setQueueCapacity(10);

        //线程名称前缀
        executor.setThreadNamePrefix("ThreadPoolTaskExecutor-");

        //队列满后，线程数量大于最大线程，直接使用调用任务的线程执行
//        ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常
//        ThreadPoolExecutor.DiscardPolicy：丢弃任务，但是不抛出异常。
//        ThreadPoolExecutor.DiscardOldestPolicy：丢弃队列最前面。
//        ThreadPoolExecutor.CallerRunsPolicy：由调用者处理该任务 。
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());

        //当调度器shutdown被调用时等待
        //当前被调度的任务完成
        executor.setWaitForTasksToCompleteOnShutdown(true);

        //除了核心线程，其他线程空闲后的最大存活时间
        executor.setKeepAliveSeconds(20);

        //加载
        executor.initialize();

        log.info("初始化线程池成功");

        return executor;
    }
}
